import subprocess
from selenium.webdriver.common.action_chains import ActionChains
from os import scandir
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from datetime import datetime
import os
import shutil
import time

options = Options()
# options.add_argument("--headless")  # 如果不需要界面可以保留此行
user_data_dir = r"C:\Users\Administrator\AppData\Local\Google\Chrome\User Data"
options.add_argument(f"user-data-dir={user_data_dir}")
driver_path = r"F:\宇宙起源推文\chromedriver.exe"  # 确保路径正确
service = Service(driver_path)
driver = webdriver.Chrome(service=service, options=options)


def get_last_three_mp4_files(directory):
	try:
		if not os.path.exists(directory):
			print(f"目录不存在: {directory}")
			return None
		
		# 仅获取.mp4文件
		mp4_files = [
			entry.path
			for entry in scandir(directory)
			if entry.is_file() and entry.name.lower().endswith('.mp4')
		]
		
		if len(mp4_files) < 3:
			print(f"目录中MP4文件不足3个，仅找到{len(mp4_files)}个")
			return None
		
		# 按名称升序
		sorted_files = sorted(
			mp4_files,
			key=lambda x: os.path.basename(x)
		)
		
		# 取最后三个文件（最新的三个）
		last_three = sorted_files[-3:]
		
		return last_three  # 返回路径列表，按时间从旧到新排列
	
	except Exception as e:
		print(f"错误: {str(e)}")
		return None


def adjust_video_aspect_ratio_ffmpeg(input_path):
	# FFmpeg 命令：动态计算黑边并填充
	ffmpeg_path = r"D:\ffmpeg\ffmpeg-7.1.1-essentials_build\bin\ffmpeg.exe"
	cmd = [
		ffmpeg_path,
		'-i', input_path,  # 输入文件
		'-vf', f'pad=width=ih*16/9:height=ih:x=(ow-iw)/2:y=0:color=black',  # 黑边参数
		'-c:a', 'copy',  # 音频流直接拷贝（不重新编码）
		'-y',  # 覆盖输出文件
		input_path + '_new.mp4'  # 输出文件
	]
	
	# 执行命令
	subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
	
	# 替换原文件（确保成功后再覆盖）
	os.remove(input_path)
	os.rename(input_path + '_new.mp4', input_path)


def move_files_to_last_subdirectory(result, target_base_dir):
	# 确保目标基础目录存在
	if not os.path.exists(target_base_dir):
		print(f"目标基础目录不存在: {target_base_dir}")
		return
	
	# 获取目标基础目录下的所有子目录
	subdirectories = [
		entry.path
		for entry in os.scandir(target_base_dir)
		if entry.is_dir()
	]
	
	if not subdirectories:
		print("目标基础目录下没有子目录")
		return
	
	# 按名称排序并获取最后一个子目录
	last_subdirectory = sorted(subdirectories)[-1]
	
	# 移动文件到最后一个子目录中
	for file_path in result:
		file_name = os.path.basename(file_path)
		destination_path = os.path.join(last_subdirectory, file_name)
		shutil.move(file_path, destination_path)
		print(f"文件 {file_name} 已移动到 {last_subdirectory}")


def scroll_to_element(driver, element):
	actions = ActionChains(driver)
	actions.move_to_element(element).perform()


def upload_file(result):
	today = datetime.now().date()
	day = today.day
	formatted_day = f"{today.day:02d}"
	formatted_day = str(int(formatted_day) + 1)
	
	driver.get("https://creator.douyin.com/creator-micro/content/upload?enter_from=dou_web")
	for i in range(2):
		driver.execute_script(
			"window.open('https://creator.douyin.com/creator-micro/content/upload?enter_from=dou_web', '_blank');")
	
	driver.switch_to.window(driver.window_handles[0])
	for i in range(3):
		driver.switch_to.window(driver.window_handles[i])
		# 上传文件
		# 输入名字，话题，时间
		upload_input = WebDriverWait(driver, 600).until(
			EC.presence_of_element_located((By.XPATH, "//input[@type='file']"))
		)
		upload_input.send_keys(result[i])
	
	hour_x = "06"
	minute_x = "00"
	for i in range(3):
		print("第" + str(i) + "个视频发布：")
		print("==========================================")
		
		driver.switch_to.window(driver.window_handles[i])
		
		file_name = os.path.basename(result[i])  # 获取文件名（带后缀）
		title = "番茄小说 大圣之彼岸世界 " + os.path.splitext(file_name)[0]  # 去掉后缀
		title_input = WebDriverWait(driver, 60).until(
			EC.presence_of_element_located(
				(By.XPATH, "//input[@placeholder='填写作品标题，为作品获得更多流量']")
			)
		)
		title_input.clear()  # 清除默认值（如果有）
		title_input.send_keys(title)
		print("标题输入成功")
		
		element = WebDriverWait(driver, 10).until(
			EC.element_to_be_clickable((By.CSS_SELECTOR, "div.ace-line[data-node='true']"))
		)
		element.click()
		element.send_keys("#大圣之彼岸世界 #番茄小说 #小说推文 #大圣归来 #玄幻小说 ")
		print("话题输入成功")
		
		checkbox = WebDriverWait(driver, 60).until(
			EC.element_to_be_clickable(
				(By.XPATH, "//label[contains(., '定时发布') and @class='radio-d4zkru one-line-pe7juM']")
			)
		)
		checkbox.click()  # 直接触发点击
		print("定时发布勾选成功")
		
		date_input = WebDriverWait(driver, 60).until(
			EC.element_to_be_clickable(
				(By.XPATH, "//input[@placeholder='日期和时间' and @class='semi-input semi-input-default']")
			)
		)
		date_input.click()  # 触发日期时间选择器
		print("日期选择勾选成功")

		date_locator = f"//div[contains(@class, 'semi-datepicker-day') and .//span[text()='{formatted_day}']]"
		date_element = WebDriverWait(driver, 60).until(
			EC.element_to_be_clickable((By.XPATH, date_locator))
		)
		date_element.click()
		print("成功勾选本月" + formatted_day + "日")

		time_switch = WebDriverWait(driver, 60).until(
			EC.element_to_be_clickable(
				(By.XPATH, "//div[contains(@class, 'semi-datepicker-switch-time')]")
			)
		)
		time_switch.click()
		print("时间选择器点击成功")
		
		hour_locator = f"//div[@class='semi-scrolllist-item-wheel undefined-list-hour']/div[@class='semi-scrolllist-list-outer']/ul/li[starts-with(text(), '{hour_x}')]"
		hour_button = WebDriverWait(driver, 60).until(
			EC.presence_of_element_located((By.XPATH, hour_locator))
		)
		scroll_to_element(driver, hour_button)
		hour_button.click()
		print("成功选择" + hour_x + "时")
		
		minute_locator = f"//div[@class='semi-scrolllist-item-wheel undefined-list-minute']/div[@class='semi-scrolllist-list-outer']/ul/li[starts-with(text(), '{minute_x}')]"
		minute_button = WebDriverWait(driver, 60).until(
			EC.presence_of_element_located((By.XPATH, minute_locator))
		)
		scroll_to_element(driver, minute_button)
		minute_button.click()
		print("成功选择" + minute_x + "分")
		
		video_locator = (
			By.XPATH, "//div[contains(@class, 'player-container-pB5Sel') and contains(@class, 'player-RaoTpQ')]/video")
		WebDriverWait(driver, 600).until(
			EC.visibility_of_element_located(video_locator),
			message="视频预览区域未加载完成"
		)
		
		recommended_cover = WebDriverWait(driver, 20).until(
			EC.element_to_be_clickable(
				(By.XPATH, "//div[@class='content-upload-new']//div[contains(@class, 'recommendCover-vWWsHB')][1]")
			)
		)
		scroll_to_element(driver, recommended_cover)  # 滚动到元素可见
		recommended_cover.click()
		print("封面选择成功")
		
		confirm_button = WebDriverWait(driver, 20).until(
			EC.element_to_be_clickable(
				(By.XPATH,
				 "//div[contains(@class, 'semi-modal semi-modal-centered semi-modal-small')]//button[contains(@class, 'semi-button-primary') and .//span[@class='semi-button-content' and text()='确定']]")
			)
		)
		confirm_button.click()
		print("点击‘确定’按钮成功")
		
		time.sleep(10)
		
		publish_button = WebDriverWait(driver, 60).until(
			EC.element_to_be_clickable(
				(By.XPATH, "//button[text()='发布' and contains(@class, 'primary-cECiOJ')]")
			)
		)
		publish_button.click()
		print("发布按钮点击成功")
		
		hour_x = str(int(hour_x) + 6)
		
		time.sleep(5)


if __name__ == "__main__":
	directory = r"C:\Users\Administrator\Downloads"
	result = get_last_three_mp4_files(directory)
	if result:
		for idx, path in enumerate(result, 1):
			print(path)
			print("正在处理中第" + str(idx) + "个...")
			adjust_video_aspect_ratio_ffmpeg(path)
			print("处理完了")
	else:
		print("未找到足够MP4文件")
	
	result = get_last_three_mp4_files(directory)
	upload_file(result)
	
	target_base_dir = r"E:\宇宙起源推文-结果\视频"
	move_files_to_last_subdirectory(result, target_base_dir)
	
	driver.quit()
	